<?php

declare(strict_types=1);


namespace App\CustHub\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Helpers\SortHelper;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\ChPermission;
use App\CustHub\Annotation\VerifySignature;
use App\CustHub\Constants\RobotApplyConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Event\SmartAnswerTrigger;
use App\CustHub\Model\ChCrowdSending;
use App\CustHub\Model\ChCrowdSendingGroup;
use App\CustHub\Model\ChSmartAnswer;
use App\CustHub\Model\ChSmartAnswerGroup;
use App\CustHub\Model\ChSmartAnswerKnowledge;
use App\CustHub\Model\ChSmartAnswerKnowledgeQuestion;
use App\CustHub\Model\ChSmartAnswerQuestion;
use App\CustHub\Model\ChWord;
use App\CustHub\Model\ChWordGroup;
use App\CustHub\Service\ChContactService;
use App\CustHub\Service\ChCorpTagService;
use App\CustHub\Service\ChCrowSendingService;
use App\CustHub\Service\ChRobotApplyService;
use App\CustHub\Service\ChRoomService;
use App\CustHub\Service\ChRoomTagService;
use App\CustHub\Service\ChSendConfigService;
use App\CustHub\Service\ChSmartTagService;
use App\CustHub\Service\CrowdInviteService;
use App\CustHub\Service\SmartAnswerService;
use App\Enum\WordTypeEnum;
use App\Exception\BusinessException;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use App\CustHub\Service\ChUserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Rule;
use Psr\EventDispatcher\EventDispatcherInterface;


#[Controller(prefix: 'ch/smart/answer'),ApiAuth,VerifySignature]
class SmartAnswerController extends BaseController
{
    #[Inject]
    protected SmartAnswerService $service;

    #[Inject]
    protected ChRobotApplyService $applyService;

    #[Inject]
    protected ChSendConfigService $sendService;

    #[Inject]
    protected ChCorpTagService $corpTagService;

    #[Inject]
    protected ChSmartTagService $ChSmartTagService;

    #[Inject]
    protected ChContactService $contactService;

    #[Inject]
    protected ChRoomService $roomService;

    #[Inject]
    protected ChCrowSendingService $chCrowSendingService;


    /**
     * 添加分组
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/add'),ChPermission('ch:smart:answer:group:add')]
    public function addGroup()
    {
//        $this->eventDispatcher->dispatch(new SmartAnswerTrigger([]));exit;
        $this -> validateParam([
            'title' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $title =$this->request->input('title');
        $mainUid = $this->request->input('main_uid');
        $pId =$this->request->input('p_id',0);
        $res = ChSmartAnswerGroup::saveGroup($uid,$mainUid,$title,$pId);
        return $this -> success('添加成功',$res);
    }

    /**
     * 修改分组
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/edit'),ChPermission('ch:smart:answer:group:edit')]
    public function editGroup()
    {
        $this -> validateParam([
            'title' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $title =$this->request->input('title');
        $id =$this->request->input('id');
        $pId =$this->request->input('p_id',0);
        $mainUid = $this->request->input('main_uid');

        $res = ChSmartAnswerGroup::saveGroup($uid,$mainUid,$title,$pId,$id);
        return $this -> success('修改成功',$res);
    }



    #[PostMapping('group/delete'),ChPermission('ch:smart:answer:group:edit')]
    public function deleteGroup()
    {
        $this -> validateParam([
            'id' => 'required',
            //'type' => 'required',
        ]);
        $id =$this->request->input('id');
        //$type =$this->request->input('type');
        //1删除分组及话术 2删除分组
//        if($type  == 1){
//            Db::transaction(function ()use($id){
//                ChSmartAnswerGroup::query() -> where('id',$id) -> delete();
//                $ids = ChSmartAnswerGroup::query() -> where('p_id',$id) -> pluck('id');
//                $ids = !empty($ids)?$ids:[];
//                $ids[] = $id;
//                ChSmartAnswerGroup::query() -> where('p_id',$id) -> delete();
//                ChSmartAnswer::query() -> whereIn('group_id',$ids) -> delete();
//            });
//
//        }else{
//            Db::transaction(function ()use($id){
//                ChSmartAnswerGroup::query() -> where('id',$id) -> delete();
//                $ids = ChSmartAnswerGroup::query() -> where('p_id',$id) -> pluck('id');
//                $ids = !empty($ids)?$ids:[];
//                $ids[] = $id;
//                ChSmartAnswerGroup::query() -> where('p_id',$id) -> delete();
//                ChSmartAnswer::query() -> whereIn('group_id',$ids) -> update(['group_id'=>0]);
//            });
//        }
        Db::transaction(function ()use($id){
            ChSmartAnswerGroup::query() -> where('id',$id) -> delete();
            //$ids = ChSmartAnswerGroup::query() -> where('p_id',$id) -> pluck('id');

            ChSmartAnswer::query() -> where('group_id',$id) -> update(['group_id'=>0]);
        });
        return $this -> success('删除成功',[]);
    }




    /**
     * 分组列表
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/list'),ChPermission('ch:smart:answer:group:list')]
    public function groupList()
    {
        $uid =$this->request->input('uid');
        $page_size =$this->request->input('page_size',15);
        $mainUid = $this->request->input('main_uid');

        $page = ChSmartAnswerGroup::query() -> where('main_uid',$mainUid) -> where('p_id',0)  -> orderByDesc('sort') -> paginate((int)$page_size);
        $list = $page -> items();
        $total = $page -> total();
        return $this -> success('获取成功',['list'=>$list,'total'=>$total]);
    }

    #[PostMapping('question/add'),ChPermission('ch:smart:answer:question:add')]
    public function addQuestion()
    {
        $this -> validateParam([
            'answer_id' => 'required',
            'title' => 'required',
            'content' => 'required',
            //'fuzzy_keyword' => 'required',
            //'keyword' => 'required',
            'sort' => 'required',
            'answer_type' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $params = $this -> request -> all();
        $res = ChSmartAnswerQuestion::saveQuestion($params);
        return $this -> success('添加成功',$res);
    }


    #[PostMapping('question/edit'),ChPermission('ch:smart:answer:question:edit')]
    public function editQuestion()
    {
        $this -> validateParam([
            'answer_id' => 'required',
            'title' => 'required',
            'content' => 'required',
            //'fuzzy_keyword' => 'required',
            //'keyword' => 'required',
            'sort' => 'required',
            'answer_type' => 'required',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $params = $this -> request -> all();
        $res = ChSmartAnswerQuestion::saveQuestion($params,$id);
        return $this -> success('添加成功',$res);
    }

    #[PostMapping('question/delete'),ChPermission('ch:smart:answer:question:delete')]
    public function deleteQuestion()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        ChSmartAnswerQuestion::query() -> where('id',$id) -> delete();
        return $this -> success('删除成功');
    }

    #[PostMapping('question/list'),ChPermission('ch:smart:answer:question:list')]
    public function questionList()
    {
        $uid =$this->request->input('uid');
        $answer_id =$this->request->input('answer_id');
        $keyword =$this->request->input('keyword');
        $page_size =$this->request->input('page_size',15);
        //$mainUid = $this->request->input('main_uid');

        $page = ChSmartAnswerQuestion::query()
            -> where('answer_id',$answer_id)
            -> when($keyword,function($query) use ($keyword) {
                !empty($keyword) && $query -> where('title','like',"%{$keyword}%");
            })
            -> orderByDesc('id')
            -> paginate((int)$page_size);
        $data = [
            'items' => $page -> items(),
            'pageInfo' => [
                'total' => $page->total(),
                'currentPage' => $page->currentPage(),
                'totalPage' => $page->lastPage(),
            ],
        ];
        return $this -> success('获取成功',$data);
    }


    #[PostMapping('question/detail'),ChPermission('ch:smart:answer:question:detail')]
    public function questionDetail()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $info = ChSmartAnswerQuestion::query() -> where('id',$id) -> first();
        if(empty($info)) return $this -> error('数据不存在',ErrorCode::NOT_ISSET);
        return $this -> success('获取成功',$info);
    }

    #[PostMapping('operate'), ChPermission('ch:smart:answer:operate')]
    public function operate()
    {
        $this->validateParam([
            'id' => 'required',
            'status' => 'required',
        ]);
        $uid = $this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $status = $this->request->input('status');
        ChSmartAnswer::query()->where('id',$id)->update(['status' => $status]);
        $ids=$this->applyService->getApplyRobot(RobotApplyConstants::SMART_ANSWER,$id);
        $this->service->clearSchemeCache($ids);
        return $this->success('操作成功');
    }

    #[PostMapping('add'),ChPermission('ch:smart:answer:add')]
    public function add()
    {
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $corpId = $this->request->input('corp_id');
        $count = ChSmartAnswer::query() -> where('uid',$uid) -> count();
        $title = "方案".$count + 1;
        $res = ChSmartAnswer::query() -> create([
            'title' => $title,
            'corp_id' => $corpId,
            'main_uid' => $mainUid,
            'answer_times_type' => 1,
            'uid' => $uid,
            'open_keyword' => 1,
            'answer_type' => 2,
            'open_image' => 1,
            'open_default' => 1,
            'answer_start' => "08:00",
            'answer_time_config' => null,
            'answer_end' => "23:59",
            'answer_limit_max' => 10,
            'answer_limit_min' => 5,
            'keyword_conf' => ChSmartAnswer::$keywordStatic,
            'image_conf' => ChSmartAnswer::$imageStatic,
            'default_conf' => ChSmartAnswer::$defaultStatic,
            'condition_conf'=>["crowd_conf"=>["type"=>1],"custom_conf"=>["type"=>1]]
        ]);
        return $this -> success('添加成功',$res);
    }


    #[PostMapping('delete'),ChPermission('ch:smart:answer:delete')]
    public function delete()
    {
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $mainUid = $this->request->input('main_uid');
        ChSmartAnswer::query() -> where('uid',$uid) -> where('id',$id)->delete();
        $ids=$this->applyService->getApplyRobot(RobotApplyConstants::SMART_ANSWER,$id);
        $this->service->clearSchemeCache($ids);
        return $this -> success('删除成功');
    }

    #[PostMapping('rename'),ChPermission('ch:smart:answer:rename')]
    public function rename()
    {
        $this -> validateParam([
            'id' => 'required',
            'title' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $title = $this->request->input('title');

        $res = ChSmartAnswer::query() -> where('id',$id) -> update(['title' => $title]);
        if($res){
            return $this -> success('修改成功');
        }
        return $this -> error('数据不存在',ErrorCode::NOT_ISSET);
    }

    #[PostMapping('edit'),ChPermission('ch:smart:answer:edit')]
    public function saveAnswer()
    {
        $this -> validateParam([
            'id' => 'required',
            'answer_times_type' => 'required',
            //'answer_start' => 'required',
            //'answer_end' => 'required',
            'answer_limit_max' => 'required',
            'answer_limit_min' => 'required',
            'answer_type' => 'required',
            'open_keyword' => 'required',
            'open_image' => 'required',
            'open_default' => 'required',
            'corp_id' => 'required',
            'save_type' => 'required',
            'robot_ids' => 'required_if:save_type,2'
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $mainUid = $this->request->input('main_uid');
        $saveType = $this->request->input('save_type');
        $params = $this->request->all();

        Db::beginTransaction();
        try {
            $res = ChSmartAnswer::saveAnswer($uid,$params,$id);
            if($res){
                if($saveType == 2){
                    //应用配置
                    $robotUserIds = $this->request->input('robot_ids');
                    if(!is_array($robotUserIds)){
                        $robotUserIds = json_decode($robotUserIds,true);
                    }
                    $answerIds = [$res -> id];
                    $this -> applyService -> batchApply($this->request->input('corp_id'),RobotApplyConstants::SMART_ANSWER,$answerIds,$robotUserIds);
                }
                //清除缓存
                $ids=$this->applyService->getApplyRobot(RobotApplyConstants::SMART_ANSWER,$id);
                $this->service->clearSchemeCache($ids);
                Db::commit();
                return $this -> success('修改成功',$res);
            }
        }catch (\Exception $e){
            Db::rollBack();
            return $this -> error($e -> getMessage());
        }

        return $this -> error('数据不存在',ErrorCode::NOT_ISSET);
    }


    #[PostMapping('copy'),ChPermission('ch:smart:answer:edit')]
    public function copy()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        Db::beginTransaction();
        try {
            $uid =$this->request->input('uid');
            $id =$this->request->input('id');
            $data=ChSmartAnswer::query()->where('id',$id)->first()->toArray();
            if(empty($data)){
                return $this -> error('数据不存在',ErrorCode::NOT_ISSET);
            }
            $data['title']=$data['title'].'-复件';
            $res = ChSmartAnswer::saveAnswer($uid,$data);
            //复制answer
            $answerList = ChSmartAnswerQuestion::query()->where('answer_id',$id)->get();
            if(!empty($answerList)){
                $answerList=$answerList->toArray();
                foreach ($answerList as $data1){
                    $data1['answer_id']=$res->id;
                    ChSmartAnswerQuestion::saveQuestion($data1);
                }
            }
            Db::commit();
            return $this -> success('复制成功',$res);
        }catch (\Exception $e){
            Db::rollBack();
            return $this -> error($e -> getMessage());
        }


    }

    #[PostMapping('list'),ChPermission('ch:smart:answer:list')]
    public function list()
    {
        $uid =$this->request->input('uid');
        $page_size =$this->request->input('page_size',15);
        $corp_id =$this->request->input('corp_id',0);
        $group_id =$this->request->input('group_id');
        $keyword =$this->request->input('keyword');
        //$mainUid = $this->request->input('main_uid');

        $query = ChSmartAnswer::query() -> where('uid',$uid);
        if($corp_id){
            $query->where('corp_id',$corp_id);
        }
        if(filled($group_id)){
            $query->where('group_id',$group_id);
        }
        if($keyword){
            $query->where('title','like',"%$keyword%");
        }
        $query-> orderByDesc('id') -> select(['open_keyword','open_image','open_default','title','id','status']);
        $page=$query -> paginate((int)$page_size);
        $list = $page -> items();
        $total = $page -> total();
        return $this -> success('获取成功',['list'=>$list,'total'=>$total]);
    }

    #[PostMapping('detail'),ChPermission('ch:smart:answer:detail')]
    public function detail()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $page_size =$this->request->input('page_size',15);
        //$mainUid = $this->request->input('main_uid');

        $detail = ChSmartAnswer::query() -> where('id',$id)  -> first();
        $detail['robots'] = $this -> applyService -> getApplyRobotsInfo(RobotApplyConstants::SMART_ANSWER,$id);
        if(empty($detail)) return $this -> error('数据不存在',ErrorCode::NOT_ISSET);
        !empty($detail['auto_smart_tag']) && $detail['auto_smart_tag_array']=$this->ChSmartTagService->getTagsByIds($detail['auto_smart_tag']);
        !empty($detail['auto_enterprise_tag']) && $detail['auto_enterprise_tag_array']=$this->corpTagService->getTagsByIds($detail['auto_enterprise_tag']);
        if(!empty($detail['custom_ids'])){
            $detail['custom_ids_array'] = $this -> contactService -> getContactByUserIds($detail['custom_ids']);
        }
        if(!empty($detail['crowd_ids'])){
            $detail['crowd_ids_array'] = $this -> roomService -> getRoomsByUserIds($detail['crowd_ids']);
        }
        if(!empty($detail['condition_conf'])) $detail['condition_conf']=$this->chCrowSendingService->formatConditionToText2($detail['condition_conf']);

        return $this -> success('获取成功',$detail);
    }

    /**
     * 应用机器人
     */
    #[PostMapping('bind'),ChPermission('ch:smart:answer:bind')]
    public function bindRobot()
    {
        $this -> validateParam([
            'answer_ids' => 'required',
            'robot_ids' => 'required',
            'corp_id' => 'required'
        ]);
        $answerIds = $this->request->input('answer_ids');
        $robotUserIds = $this->request->input('robot_ids');
        $corpId = $this->request->input('corp_id');
        if(!is_array($answerIds)){
            $answerIds = json_decode($answerIds,true);
        }

        if(!is_array($robotUserIds)){
            $robotUserIds = json_decode($robotUserIds,true);
        }

        $this -> applyService -> batchApply($corpId,RobotApplyConstants::SMART_ANSWER,$answerIds,$robotUserIds);
        return $this -> success('绑定成功');
    }

    #[PostMapping('apply_log'),ChPermission('ch:smart:answer:apply_log')]
    public function getApplyLog()
    {
        $this -> validateParam([
            'query_type' => 'required',
            'corp_id' => 'required'
        ]);
        $queryType = $this->request->input('query_type');
        $corpId = $this->request->input('corp_id');

        $res = $this -> applyService -> getApplyLog(ChSmartAnswer::getModel() -> getTable(),RobotApplyConstants::SMART_ANSWER,$corpId,$queryType);
        return $this -> success($res);
    }

    #[PostMapping('set_field'),ChPermission('ch:smart:answer:set_field')]
    public function setField()
    {
        $this -> validateParam([
            'field' => [
                'required',
                Rule::in(['status']),
            ],
            'value' => 'required|boolean',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $value =$this->request->input('value');
        $field =$this->request->input('field');
        ChSmartAnswer::query() -> where('id',$id) -> update([$field => $value]);
        return $this -> success('操作成功');
    }

    #[PostMapping('robot/apply_list'),ChPermission('ch:smart:answer:robot:list')]
    public function robotApplyList()
    {
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');

        $data=$this -> applyService -> getApplyRobotsInfo(RobotApplyConstants::SMART_ANSWER,$id);
        return $this -> success('获取成功',$data);
    }

    /**
     * 批量设置下发机器人状态
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('set_robot_batch'),ChPermission('ch:smart:answer:set_field_batch')]
    public function setFieldBatch()
    {
        $this -> validateParam([
            'id' => 'required',
            'type' => 'required',
            'corp_id' => 'required',
            'robot_ids' => 'required',
        ]);
        //type 1批量取消  2批量开启  3批量关闭
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $type =$this->request->input('type');
        $corpId = $this->request->input('corp_id');
        $robotIds = $this->request->input('robot_ids');
        $robotIds = is_array($robotIds)?$robotIds:json_decode($robotIds,true);
        if($type==1){
            $this -> applyService -> robotBatchCancelApply($corpId,RobotApplyConstants::SMART_ANSWER,$id,$robotIds);
        }
        if($type==2){
            $this -> applyService -> robotBatchOpenApply($corpId,RobotApplyConstants::SMART_ANSWER,$id,$robotIds);
        }
        if($type==3){
            $this -> applyService -> robotBatchCloseApply($corpId,RobotApplyConstants::SMART_ANSWER,$id,$robotIds);
        }
        $this->service->clearSchemeCache($robotIds);
        return $this -> success('操作成功');
    }


    /**
     * 添加分组
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('knowledge/add'),ChPermission('ch:smart:answer:knowledge:add')]
    public function addKnowledge()
    {
        $this -> validateParam([
            'title' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $title =$this->request->input('title');
        $mainUid = $this->request->input('main_uid');
        $pId =$this->request->input('p_id',0);
        $res = ChSmartAnswerKnowledge::saveKnowledge($uid,$mainUid,$title);
        return $this -> success('添加成功',$res);
    }

    /**
     * 修改知识库
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('knowledge/edit'),ChPermission('ch:smart:answer:knowledge:edit')]
    public function editKnowledge()
    {
        $this -> validateParam([
            'title' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $title =$this->request->input('title');
        $mainUid = $this->request->input('main_uid');
        $id =$this->request->input('id',0);
        $res = ChSmartAnswerKnowledge::saveKnowledge($uid,$mainUid,$title,$id);
        return $this -> success('添加成功',$res);
    }

    #[PostMapping('knowledge/delete'),ChPermission('ch:smart:answer:knowledge:delete')]
    public function deleteKnowledge()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $title =$this->request->input('title');
        $mainUid = $this->request->input('main_uid');
        $id =$this->request->input('id',0);
        $res = ChSmartAnswerKnowledge::where('id',$id)->delete();
        return $this -> success('删除成功');
    }

    #[PostMapping('knowledge/copy'),ChPermission('ch:smart:answer:edit')]
    public function copyKnowledge()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        Db::beginTransaction();
        try {
            $uid =$this->request->input('uid');
            $mainUid =$this->request->input('main_uid');
            $id =$this->request->input('id');
            $data=ChSmartAnswerKnowledge::query()->where('id',$id)->first()->toArray();
            if(empty($data)){
                return $this -> error('数据不存在',ErrorCode::NOT_ISSET);
            }
            $data['title']=$data['title'].'-复件';
            $res = ChSmartAnswerKnowledge::saveKnowledge($uid,$mainUid,$data['title']);
            //复制answer
            $answerList = ChSmartAnswerKnowledgeQuestion::query()->where('knowledge_id',$id)->get();
            if(!empty($answerList)){
                $answerList=$answerList->toArray();
                foreach ($answerList as $data1){
                    $data1['knowledge_id']=$res->id;
                    ChSmartAnswerKnowledgeQuestion::saveQuestion($data1);
                }
            }
            Db::commit();
            return $this -> success('复制成功',$res);
        }catch (\Exception $e){
            Db::rollBack();
            return $this -> error($e -> getMessage());
        }
    }


    /**
     * 知识库列表
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('knowledge/list'),ChPermission('ch:smart:answer:knowledge:list')]
    public function knowledgeList()
    {
        $uid =$this->request->input('uid');
        $page_size =$this->request->input('page_size',15);
        $mainUid = $this->request->input('main_uid');
        $accountId = $this->request->input('account_id');
        $keyword = $this->request->input('keyword');
        $query =  ChSmartAnswerKnowledge::query();
        if($accountId){
            $query -> where('uid',$accountId);
        }else{
            $query -> where('main_uid',$mainUid) ;
        }
        if($keyword){
            $query -> where('title','like',"%$keyword%") ;
        }

        $page = $query ->with(['user' => function ($q) {
            $q->select('id', 'nickname');
        }]) -> orderByDesc('id') -> paginate((int)$page_size);
        foreach ($page as $item){
            $item['total'] = ChSmartAnswerKnowledgeQuestion::query() -> where('knowledge_id',$item -> id) -> count();
        }
        $list = $page -> items();
        $total = $page -> total();
        return $this -> success('获取成功',['list'=>$list,'total'=>$total]);
    }



    /**
     * 知识库详情
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('knowledge/detail'),ChPermission('ch:smart:answer:knowledge:detail')]
    public function knowledgeDetail()
    {
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $detail = ChSmartAnswerKnowledge::query() -> where('id',$id) -> first();
        $detail -> question_list = ChSmartAnswerKnowledgeQuestion::query() -> where('knowledge_id',$detail -> id) -> get();
        return $this -> success('获取成功',$detail);
    }




    #[PostMapping('knowledge/question/add'),ChPermission('ch:smart:answer:knowledge:question:add')]
    public function addKnowledgeQuestion()
    {
        $this -> validateParam([
            'knowledge_id' => 'required',
            'title' => 'required',
            'content' => 'required',
            'fuzzy_keyword' => 'required',
            'keyword' => 'required',
            'sort' => 'required',
            'answer_type' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $params = $this -> request -> all();
        $res = ChSmartAnswerKnowledgeQuestion::saveQuestion($params);
        return $this -> success('添加成功',$res);
    }


    #[PostMapping('knowledge/question/edit'),ChPermission('ch:smart:answer:knowledge:question:edit')]
    public function editKnowledgeQuestion()
    {
        $this -> validateParam([
            'knowledge_id' => 'required',
            'title' => 'required',
            'content' => 'required',
            'fuzzy_keyword' => 'required',
            'keyword' => 'required',
            'sort' => 'required',
            'answer_type' => 'required',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $params = $this -> request -> all();
        $res = ChSmartAnswerKnowledgeQuestion::saveQuestion($params,$id);
        return $this -> success('编辑成功',$res);
    }

    #[PostMapping('knowledge/question/delete'),ChPermission('ch:smart:answer:knowledge:question:delete')]
    public function deleteKnowledgeQuestion()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        ChSmartAnswerKnowledgeQuestion::query() -> where('id',$id) -> delete();
        return $this -> success('删除成功');
    }

    #[PostMapping('knowledge/question/list'),ChPermission('ch:smart:knowledge:question:list')]
    public function KnowledgeQuestionList()
    {
        $uid =$this->request->input('uid');
        $knowledge_id =$this->request->input('knowledge_id');
        $page_size =$this->request->input('page_size',15);
        //$mainUid = $this->request->input('main_uid');

        $page = ChSmartAnswerKnowledgeQuestion::query() -> where('knowledge_id',$knowledge_id)  -> orderByDesc('sort')  -> paginate((int)$page_size);
        $data = [
            'items' => $page -> items(),
            'pageInfo' => [
                'total' => $page->total(),
                'currentPage' => $page->currentPage(),
                'totalPage' => $page->lastPage(),
            ],
        ];
        return $this -> success('获取成功',$data);
    }


    #[PostMapping('knowledge/apply'),ChPermission('ch:smart:answer:knowledge:apply')]
    public function applyKnowledge()
    {
        $this -> validateParam([
            'id' => 'required',
            'answer_id' => 'required'
        ]);
        $id = $this->request->input('id');
        $answer_id = $this->request->input('answer_id');
        $knowledgeQuestionList = ChSmartAnswerKnowledgeQuestion::query() -> where('knowledge_id',$id) -> get();
        if(empty($knowledgeQuestionList)) $this -> error('数据不存在',ErrorCode::NOT_ISSET);

        Db::beginTransaction();
        try {
            ChSmartAnswerQuestion::query() -> where('answer_id',$answer_id) -> delete();
            foreach ($knowledgeQuestionList as $knowledgeQuestion){
                $params = [
                    'answer_id' => $answer_id,
                    'title' => $knowledgeQuestion -> title,
                    'content' => $knowledgeQuestion -> content,
                    'fuzzy_keyword' => $knowledgeQuestion -> fuzzy_keyword,
                    'keyword' => $knowledgeQuestion -> keyword,
                    'sort' => $knowledgeQuestion -> sort,
                    'answer_type' => $knowledgeQuestion -> answer_type,
                ];
                ChSmartAnswerQuestion::saveQuestion($params);
            }
            Db::commit();
            return $this -> success('操作成功');
        }catch (\Exception $e){
            Db::rollBack();
            return $this -> error($e -> getMessage());
        }

    }



    #[PostMapping('system/list'), ChPermission('ch:smart:answer:system:list')]
    public function systemList()
    {
        $params = $this->request->all();
        $params['type'] = SendConfigConstants::SMART_ANSWER;
        $list = $this->sendService->getConfigList($params);
        return $this->success('获取成功', $list);
    }

    #[PostMapping('system/detail'), ChPermission('ch:smart:answer:system:detail')]
    public function systemDetail()
    {
        $this->validateParam([
            'robot_id' => 'required',
        ]);

        $mainUid = $this->request->input('main_uid');
        $uid = $this->request->input('uid');
        $robot_id = $this->request->input('robot_id');
        $detail = $this->sendService->getConfig(SendConfigConstants::SMART_ANSWER, $uid, $robot_id);
        return $this->success('获取成功', $detail);
    }

    #[PostMapping('system/save'), ChPermission('ch:smart:answer:system:save')]
    public function saveSystem()
    {
        $this->validateParam([
            'robot_ids' => 'required',
            'value' => 'required',
        ]);
        $mainUid = $this->request->input('main_uid');
        $uid = $this->request->input('uid');
        $corp_id = $this->request->input('corp_id');
        $robot_ids = $this->request->input('robot_ids');
        $value = $this->request->input('value');
        $robot_ids = !is_array($robot_ids) ? json_decode($robot_ids, true) : $robot_ids;
        foreach ($robot_ids as $robot_id) {
            $this->sendService->saveConfig(SendConfigConstants::SMART_ANSWER, $uid, $mainUid, $corp_id, $robot_id, $value);
        }
        return $this->success('保存成功', []);
    }

}